<template>
  <div class="app-container">
    <div class="header">
      <el-button type="primary" size="mini" @click="handleAdd">
        新增会员权益
      </el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="tableList"
      @sort-change="handleSortChange"
    >
      <el-table-column label="权益名称" prop="raiName" />
      <el-table-column label="间隔天数" prop="intervalNum" />
      <el-table-column label="权益数量" prop="raiNum" />
      <el-table-column label="权益可领取次数" prop="raiAvailableNum" />
      <el-table-column label="权益状态">
        <template slot-scope="scope">
          {{ scope.row.raiStatus == 1 ? "已上架" : "已下架" }}
        </template>
      </el-table-column>
      <el-table-column label="排序值" prop="sort" />
      <el-table-column label="更新人" prop="updateByName" width="100">
        <template slot-scope="scope">
          {{ formatTableValue(scope.row.updateByName) }}
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
        sortable="custom"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button type="text" @click="handleUnmount(scope.row)">
            {{ scope.row.raiStatus == 0 ? "上架" : "下架" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      custom-class="custom-dialog"
      @close="closeDialog" :close-on-click-modal="false"
    >
      <el-form
        ref="userRightsform"
        :model="form"
        :rules="rules"
        label-position="top"
      >
        <el-form-item label="权益名称：" prop="raiName" class="">
          <div class="flex flex-col">
            <el-input
              v-model="form.raiName"
              placeholder="请输入"
              maxlength="20"
            />
            <span class="custom-placeholder"
              >显示给顾客看的，输入具体名称即可</span
            >
          </div>
        </el-form-item>
        <el-form-item label="间隔天数：" prop="intervalNum">
          <div class="flex flex-col">
            <el-input
              v-number-input
              maxlength="5"
              v-model="form.intervalNum"
              placeholder="请输入"
            />
            <span class="custom-placeholder"
              >顾客可多次领取权益的间隔天数，为0则仅限1次</span
            >
          </div>
        </el-form-item>
        <el-form-item label="权益数量：" prop="raiNum">
          <div class="flex flex-col">
            <el-input
              v-number-input
              maxlength="5"
              v-model="form.raiNum"
              placeholder="请输入"
            />
            <span class="custom-placeholder">单次领取权益的数量</span>
          </div>
        </el-form-item>
        <el-form-item label="权益可领取次数：" prop="raiAvailableNum">
          <div class="flex flex-col">
            <el-input
              v-number-input
              maxlength="5"
              v-model="form.raiAvailableNum"
              placeholder="请输入"
            />
            <span class="custom-placeholder">大于1次时，间隔天数不能为0</span>
          </div>
        </el-form-item>
        <el-form-item label="显示排序值：" prop="sort">
          <div class="flex flex-col">
            <el-input
              v-number-input
              maxlength="5"
              v-model="form.sort"
              placeholder="请输入"
            />
          </div>
        </el-form-item>
        <el-form-item label="权益商品：">
          <template slot="label">
            <span>权益商品：</span>
            <el-button type="primary" @click="openSelectProduct"
              >选择商品</el-button
            >
          </template>

          <el-table :data="selectProductList">
            <el-table-column label="商品头图">
              <template slot-scope="scope">
                <div class="flex items-center">
                  <el-image
                    style="width: 40px; height: 40px; margin-right: 12px"
                    :src="scope.row.goodsPhoto"
                    fit="cover"
                  ></el-image>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="goodsName" />
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="text" @click="handleRemove(scope.row)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm('userRightsform')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 选择商品弹窗 -->
    <select-product-dialog
      ref="selectProductRef"
      @handle-select="handleSelectProduct"
    ></select-product-dialog>
  </div>
</template>

<script>
import {
  getRightConfigListAPI,
  addRightConfigAPI,
  updateRightConfigAPI,
  getGoodsRaiListAPI,
} from "@/api/system/member";
import SelectProductDialog from "@/components/Product/SelectProductDialog.vue";

export default {
  name: "RightsConfig",
  components: { SelectProductDialog },
  data() {
    return {
      loading: true,
      tableList: [],
      open: false,
      total: 1,
      queryParams: {
        pageNum: 1,
        pageSize: 15,
      },
      title: "",
      form: {
        raiName: "",
        intervalNum: "",
        raiNum: "",
        raiAvailableNum: "",
        sort: "",
        raiGoods: [],
      },
      rules: {
        raiName: [
          {
            required: true,
            message: "权益名称必填，限输入20个字",
            trigger: "blur",
          },
        ],
        intervalNum: [
          {
            required: true,
            message: "间隔天数必填，限输入5个字符",
            trigger: "blur",
          },
        ],
        raiNum: [
          {
            required: true,
            message: "权益数量必填，限输入5个字符",
            trigger: "blur",
          },
        ],
        raiAvailableNum: [
          {
            required: true,
            message: "权益可领取次数必填，限输入5个字符",
            trigger: "blur",
          },
        ],
        sort: [
          {
            required: true,
            message: "排序值必填，限输入5个字符",
            trigger: "blur",
          },
        ],
      },
      selectProductList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      getRightConfigListAPI(this.queryParams).then((response) => {
        this.tableList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    handleAdd() {
      this.open = true;
      this.title = "新增会员权益";
      this.form = {
        raiName: "",
        intervalNum: "",
        raiNum: "",
        raiAvailableNum: "",
        sort: "",
        raiGoods: [],
      };
    },
    handleEdit(row) {
      console.log(row, "编辑");
      this.open = true;
      this.title = "编辑会员权益";
      this.form = JSON.parse(JSON.stringify(row));
      if (row.raiGoodsParam != null) {
        getGoodsRaiListAPI({ raiGoods: row.raiGoodsParam.slice(1, -1) }).then(
          (response) => {
            if (response.code === 200) {
              this.selectProductList = response.data;
            }
          }
        );
      }
    },
    handleUnmount(row) {
      let title = "";
      if (row.raiStatus == 0) {
        title = "请确认是否上架?";
      } else {
        title = "下架后该权益新会员不可见，是否确认下架?";
      }

      this.$confirm(title, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateRightConfigAPI({
            id: row.id,
            raiStatus: row.raiStatus == 0 ? 1 : 0,
          }).then((response) => {
            if (response.code === 200) {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: row.raiStatus == 0 ? "已取消上架" : "已取消下架",
          });
        });
    },
    openSelectProduct() {
      this.$refs.selectProductRef.openSelectProduct();
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid, errorObj) => {
        if (valid) {
          console.log(this.form, "form");
          let p = JSON.parse(JSON.stringify(this.form));
          p.raiGoods = this.selectProductList.map((item) => item.id);
          // delete p.selectProductList;
          let res = null;
          if (this.form.id != undefined) {
            res = await updateRightConfigAPI(p);
            if (res.code === 200) {
              this.getList();
              this.open = false;
            }
          } else {
            res = await addRightConfigAPI(p);
            if (res.code === 200) {
              this.getList();
              this.open = false;
            }
          }
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    closeDialog() {
      this.open = false;
      this.resetForm("userRightsform");
    },
    handleSelectProduct(row) {
      console.log(row, "选择了");
      // 判断是否存在相同 id 的商品
      const isExist = this.selectProductList.some((item) => item.id === row.id);
      if (!isExist) {
        this.selectProductList.push(row);
        this.$refs.selectProductRef?.close();
      } else {
        this.$message.warning("该商品已存在，无需重复添加");
      }
    },
    handleRemove(row) {
      const matchIndex = this.selectProductList.findIndex(
        (item) => item.id === row.id
      );
      this.selectProductList.splice(matchIndex, 1);
    },
  },
};
</script>
<style lang="scss" scoped>
.header {
  display: flex;
  justify-content: end;
  margin-bottom: 12px;
}

.product-form-item {
  display: flex;

  .input {
    width: 60%;
  }

  .product-dialog-btns {
    flex: 1;
    margin-left: 20px;
  }
}

::v-deep .el-form--label-top .el-form-item__label {
  padding-bottom: 0;
}
</style>
